package com.code.refactoring.字节码;

import org.apache.dubbo.common.compiler.support.JavassistCompiler;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;

public class JavassistCompilerTest {
    @Test
    public void testCompileJavaClass() throws Exception {
        JavassistCompiler compiler = new JavassistCompiler();
        Class<?> clazz = compiler.compile(getSimpleCode(), JavassistCompiler.class.getClassLoader());

        // Because javassist compiles using the caller class loader, we should't use HelloService directly
        Object instance = clazz.newInstance();
        Method sayHello = instance.getClass().getMethod("sayHello");
        Assertions.assertEquals("Hello world!", sayHello.invoke(instance));
    }

    @Test
    public void testCompileJavaClassWhtiParam() throws Exception {
        JavassistCompiler compiler = new JavassistCompiler();
        Class<?> clazz = compiler.compile(getSimpleCodeWithParam(), JavassistCompiler.class.getClassLoader());

        // Because javassist compiles using the caller class loader, we should't use HelloService directly
        Object instance = clazz.newInstance();
        Method sayHello = instance.getClass().getMethod("sayHello", String.class, String.class);
        Object invoke = sayHello.invoke(instance, "wangxi", "可格式化的json");
        System.out.println(invoke);
    }

    public final static AtomicInteger SUBFIX = new AtomicInteger(8);

    String getSimpleCode() {
        StringBuilder code = new StringBuilder();
//        code.append("package org.apache.dubbo.common.compiler.support;");

        code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " implements HelloService {");
        code.append("   public String sayHello() { ");
        code.append("       return \"Hello world!\"; ");
        code.append("   }");
        code.append("}");
        return code.toString();
    }

    String getSimpleCodeWithParam() {
        StringBuilder code = new StringBuilder();
//        code.append("package org.apache.dubbo.common.compiler.support;");

        code.append("public class HelloServiceImpl" + SUBFIX.getAndIncrement() + " implements HelloService {");
        code.append("   public String sayHello(String username, String json) { ");
        code.append("       return \"Hello world!\" + username; ");
        code.append("   }");
        code.append("}");
        return code.toString();
    }
}
